package com.cloudcc.boot.oaservice;

import com.cloudcc.boot.core.CCObject;
import com.cloudcc.boot.core.CCService;
import com.cloudcc.boot.web.OA_Token;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cloudcc.boot.core.CCService.userInfo;

@Controller
@RequestMapping(value = "/api")
@Slf4j
@Api(value = "", tags = {"Rustful"}, description = "")
public class oaUserClass {
    @Value("${system.oaurl:''}")
    public String oaurl;
    @Value("${system.localurl:''}")
    public String localurl;

    @Autowired
    public OA_Token oa;

    @ResponseBody
    @RequestMapping(value = "/getOaUser", produces = "text/html;charset=UTF-8")
    @ApiOperation(value = "")
    public String getOaUser(HttpServletRequest request, HttpServletResponse response) {
        JSONObject returncontent = new JSONObject();
        String day = request.getParameter("day");//日期
        CCService cs = new CCService(userInfo);
        CCObject interfacerecordObj = new CCObject("interfacerecord");//接口同步记录
        interfacerecordObj.put("url", localurl + "/api/getOaUser");//url
        interfacerecordObj.put("crcs", "day=" + day);//传入参数

        try {
            String oataken = oa.getoken();

            Map<String, String> deptMap = new HashMap<String, String>();//部门
            Map<String, String> jobMap = new HashMap<String, String>();//岗位
            Map<String, JSONObject> usermap = new HashMap<String, JSONObject>();//人员
            //获取部门列表
            String dept_str = getDepartment(oataken);
            if (dept_str.length() > 0) {
                JSONObject returnobj = JSONObject.fromObject(dept_str);
                String code = returnobj.getString("code");
                if ("1".equals(code)) {
                    JSONObject dataobj = returnobj.getJSONObject("data");
                    JSONArray data_arr = dataobj.getJSONArray("dataList");
                    log.info("接口返回部门列表=========size{}=======" + data_arr.size());
                    if (data_arr.size() > 0) {
                        for (int i = 0; i < data_arr.size(); i++) {
                            JSONObject obj = data_arr.getJSONObject(i);
                            String id = obj.getString("id") == null ? "" : obj.getString("id") + "";//id
                            String name = obj.getString("departmentname") == null ? "" : obj.getString("departmentname") + "";//name
                            if (!deptMap.containsKey(id)) {
                                deptMap.put(id, name);
                            }
                        }
                    }
                } else {
                    log.info("接口部门信息列表错误：" + dept_str);
                }
            }
            //获取岗位列表
            String title_str = getJobtitle(oataken);
            if (title_str.length() > 0) {
                JSONObject returnobj = JSONObject.fromObject(title_str);
                String code = returnobj.getString("code");
                if ("1".equals(code)) {
                    JSONObject dataobj = returnobj.getJSONObject("data");
                    JSONArray data_arr = dataobj.getJSONArray("dataList");
                    log.info("接口返回岗位列表=========size{}=======" + data_arr.size());
                    if (data_arr.size() > 0) {
                        for (int i = 0; i < data_arr.size(); i++) {
                            JSONObject obj = data_arr.getJSONObject(i);
                            String id = obj.getString("id") == null ? "" : obj.getString("id") + "";//id
                            String name = obj.getString("jobtitlename") == null ? "" : obj.getString("jobtitlename") + "";//name
                            if (!jobMap.containsKey(id)) {
                                jobMap.put(id, name);
                            }
                        }
                    }
                } else {
                    log.info("接口岗位信息列表错误：" + title_str);
                }
            }

            //获取人员信息列表
            String usre_str = getUser(oataken, day);
            if (usre_str.length() > 0) {
                JSONObject returnobj = JSONObject.fromObject(usre_str);
                String code = returnobj.getString("code");
                if ("1".equals(code)) {
                    JSONObject dataobj = returnobj.getJSONObject("data");
                    JSONArray data_arr = dataobj.getJSONArray("dataList");
                    log.info("接口返回人员信息列表=========size{}=======" + data_arr.size());
                    if (data_arr.size() > 0) {
                        for (int i = 0; i < data_arr.size(); i++) {
                            JSONObject obj = data_arr.getJSONObject(i);
                            String accounttype = obj.getString("accounttype") == null ? "" : obj.getString("accounttype") + "";//主次账号标志
//                            if ("1".equals(accounttype)) {//只取主账号：1 次账号 , 其他 主账号
//                                continue;
//                            }
                            String id = obj.getString("id") == null ? "" : obj.getString("id") + "";//id
                            String lastname = obj.getString("lastname") == null ? "" : obj.getString("lastname") + "";//人员名称
                            String workcode = obj.getString("workcode") == null ? "" : obj.getString("workcode") + "";//编号
                            String departmentid = obj.getString("departmentid") == null ? "" : obj.getString("departmentid") + "";//部门id
                            String departmentname = obj.getString("departmentname") == null ? "" : obj.getString("departmentname") + "";//部门名称
                            String jobtitle = obj.getString("jobtitle") == null ? "" : obj.getString("jobtitle") + "";//岗位id
                            String subcompanyname = obj.getString("subcompanyname") == null ? "" : obj.getString("subcompanyname") + "";//分部名称
                            String subcompanyid = obj.getString("subcompanyid1") == null ? "" : obj.getString("subcompanyid1") + "";//分部id
                            String jobname = "";//岗位名称
                            if (jobMap.containsKey(jobtitle)) {
                                jobname = jobMap.get(jobtitle);
                            }
                            JSONObject userobj = new JSONObject();
                            userobj.put("oaid", id);//人员ID
                            userobj.put("name", lastname);//人员名称
                            userobj.put("ygbh", workcode);//员工编号
                            userobj.put("oabmid", departmentid);//部门ID
                            userobj.put("oabmname", departmentname);//部门名称
                            userobj.put("oagwid", jobtitle);//岗位id
                            userobj.put("oagwname", jobname);//岗位名称
                            userobj.put("subcompanyid", subcompanyid);//分部id
                            userobj.put("subcompanyname", subcompanyname);//分部名称
                            if ("1".equals(accounttype)) {//1 次账号 , 其他 主账号
                                userobj.put("accounttype", "次账号");//账号类型
                            }else{
                                userobj.put("accounttype", "主账号");//账号类型
                            }
                            if (!usermap.containsKey(id)) {
                                usermap.put(id, userobj);
                            }
                        }
                    }
                } else {
                    log.info("接口返回人员信息列表错误：" + usre_str);
                }
            }

//            log.info("待更新OA人员map================"+usermap.toString());
            /**
             * 数据传入CRM
             */
            //OA部门传入CRM
            List<String> oadeplist = new ArrayList<String>();
            if (deptMap.size() > 0) {
                for (String key : deptMap.keySet()) {
                    String oaid = key;//部门ID
                    String name = deptMap.get(oaid);
                    List<CCObject> oadepList = cs.cquery("oadepartment", "oaid='" + oaid + "'");
                    if (oadepList.size() > 0) {
                        CCObject depObj = oadepList.get(0);
                        depObj.put("name", name);
                        depObj.put("oaid", oaid);
                        cs.update(depObj);
                    } else {
                        CCObject depObj = new CCObject("oadepartment");
                        depObj.put("name", name);
                        depObj.put("oaid", oaid);
                        cs.insert(depObj);
                    }
                    oadeplist.add(oaid);
                }
            }
            //OA人员传入CRM
            List<String> oauserlist = new ArrayList<String>();
            if (usermap.size() > 0) {
                for (String key : usermap.keySet()) {
                    String oaid = key;//人员ID
                    JSONObject userjson = usermap.get(oaid);
                    String name = userjson.getString("name");
                    String ygbh = userjson.getString("ygbh");
                    String oabmid = userjson.getString("oabmid");
                    String oabmname = userjson.getString("oabmname");
                    String oagwid = userjson.getString("oagwid");
                    String oagwname = userjson.getString("oagwname");
                    String subcompanyid = userjson.getString("subcompanyid");
                    String subcompanyname = userjson.getString("subcompanyname");
                    String accounttype = userjson.getString("accounttype");
                    List<CCObject> oauserList = cs.cquery("oayg", "oaid='" + oaid + "'");
                    if (oauserList.size() > 0) {
                        CCObject userObj = oauserList.get(0);
                        userObj.put("name", name);
                        userObj.put("ygbh", ygbh);
                        userObj.put("oabmid", oabmid);
                        userObj.put("oabmname", oabmname);
                        userObj.put("oagwid", oagwid);
                        userObj.put("oagwname", oagwname);
                        userObj.put("subcompanyid", subcompanyid);
                        userObj.put("subcompanyname", subcompanyname);
                        userObj.put("accounttype", accounttype);
                        cs.update(userObj);
                    } else {
                        CCObject userObj = new CCObject("oayg");
                        userObj.put("name", name);
                        userObj.put("oaid", oaid);
                        userObj.put("ygbh", ygbh);
                        userObj.put("oabmid", oabmid);
                        userObj.put("oabmname", oabmname);
                        userObj.put("oagwid", oagwid);
                        userObj.put("oagwname", oagwname);
                        userObj.put("subcompanyid", subcompanyid);
                        userObj.put("subcompanyname", subcompanyname);
                        userObj.put("accounttype", accounttype);
                        cs.insert(userObj);
                    }
                    oauserlist.add(oaid);
                }
            }

            interfacerecordObj.put("zxzt", "处理成功");//执行状态

            returncontent.put("result", "true");
            returncontent.put("returncode", "S");
            returncontent.put("returninfo", "");
            returncontent.put("data", "oauserlist.size()：" + oauserlist.size()+"~~~oadeplist.size():"+oadeplist.size());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.info("错误信息：" + e);
            interfacerecordObj.put("zxzt", "处理失败");//执行状态

            returncontent.put("result", "false");
            returncontent.put("returncode", "S");
            returncontent.put("returninfo", e.getMessage());
            returncontent.put("data", "success");
        } finally {
            log.info("接口返回信息================" + returncontent.toString());
            interfacerecordObj.put("fhcs", returncontent.toString());//返回参数
            cs.insert(interfacerecordObj);
        }
        return returncontent.toString();
    }

    /**
     * 获取人员信息列表
     *
     * @param token
     * @param day
     * @return
     */
    public String getUser(String token, String day) {
        CCService cs = new CCService(userInfo);
        String path = oaurl + "/api/hrm/resful/getHrmUserInfoWithPage";
        //传入参数
        JSONObject params = new JSONObject();
        JSONObject param = new JSONObject();
        param.put("pagesize", 10000);
        if (day.length() > 0) {
            param.put("modified", day);
        }
        params.put("params", param);
        //调用获接口
        String return_str = cs.oaSendPost(path, token, params.toString());
        return return_str;
    }

    /**
     * 获取岗位列表
     *
     * @param token
     * @return
     */
    public String getDepartment(String token) {
        CCService cs = new CCService(userInfo);
        String path = oaurl + "/api/hrm/resful/getHrmdepartmentWithPage";
        //传入参数
        JSONObject params = new JSONObject();
        JSONObject param = new JSONObject();
        param.put("pagesize", 10000);
        params.put("params", param);
        //调用获接口
        String return_str = cs.oaSendPost(path, token, params.toString());
        return return_str;
    }

    /**
     * 获取部门列表
     *
     * @param token
     * @return
     */
    public String getJobtitle(String token) {
        CCService cs = new CCService(userInfo);
        String path = oaurl + "/api/hrm/resful/getJobtitleInfoWithPage";
        //传入参数
        JSONObject params = new JSONObject();
        JSONObject param = new JSONObject();
        param.put("pagesize", 10000);
        params.put("params", param);
        //调用获接口
        String return_str = cs.oaSendPost(path, token, params.toString());
        return return_str;
    }
}
